#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h> // struct sockaddr_in
#include <arpa/inet.h>  // s+truct sockaddr_in
#include <cstring>
#include "err.hpp"
#include <pthread.h>
using std::cerr;
using std::cout;
using std::endl;

static void usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << "serverip serverport\n"
              << std::endl;
}

// 不断收消息
void *recver(void *args)
{
    int sock = *(static_cast<int *>(args));

    while (true)
    {
        char buf[1024];
        struct sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        int n = recvfrom(sock, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&tmp, &len);
        if (n > 0)
        {
            buf[n] = '\0';
            cout << "Server Echo# " << buf << endl; //1号fd
        }
    }
}

int main(int argc, char *argv[])
{

    if (argc != 3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }

    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    // 1.创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        cerr << "Create socket error\n";
        exit(SOCKET_ERR);
    }
    // 多线程化: 一个线程发消息，一个线程收消息
    pthread_t tid;
    pthread_create(&tid, nullptr, recver, &sock);

    // 2.绑定ip和端口，客户端不要程序员自己绑定,交给系统自动绑定

    while (true)
    {
        std::string msg;
        cerr << "Please Enter# "; //2号fd
        std::getline(std::cin, msg);

        // 首次调用系统调用，操作系统自动帮我们绑定端口和ip了
        sendto(sock, msg.c_str(), msg.size(), 0, (struct sockaddr *)&server, sizeof(server));
    }

    return 0;
}